﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace OrangePrj.Forms
{
    public partial class FormSetDependences : Form
    {
        #region Приватные Переменные
        private Work selectedWork;
        private Project projectCopy;
        private WorkList availableWorkList;
        private List<WorkItem> workItemList;
        private bool first;
        #endregion

        #region Публичные Переменные

        public Project project;

        #endregion

        #region Конструкторы
        public FormSetDependences()
        {
            InitializeComponent();
        }
        public FormSetDependences(Project project, Work selectedWork) : this()
        {
            first = true;
            this.project = project;
            projectCopy = (Project)project.Clone();

            foreach (Work w in projectCopy.worklist)
            {
                cbxWorks.Items.Add(w.Name);
            }

            this.selectedWork = projectCopy.worklist.getWorkByName(selectedWork.Name);

            workItemList = new List<WorkItem>();
            foreach (Work w in projectCopy.worklist)
            {
                workItemList.Add(new WorkItem(w));
            }

            setListViewWorks();
            cbxWorks.SelectedItem = selectedWork.Name;

            btnApply.Enabled = false;
        }
        #endregion

        #region Приватные методы

        /// <summary>
        /// Заполняет список работ
        /// </summary>
        private void setListViewWorks()
        {
            listViewWorks.Items.Clear();

            workItemList = new List<WorkItem>();
            foreach (Work w in projectCopy.worklist)
            {
                workItemList.Add(new WorkItem(w));
            }

            foreach (WorkItem workItem in workItemList)
            {
                if (workItem.Text != selectedWork.Name)
                {
                    listViewWorks.Items.Add(workItem);
                    foreach (Work w in selectedWork.DepWorks)
                    {
                        if (w.Name == workItem.Text)
                        {
                            workItem.Checked = true;
                        }
                    }
                }
            }

            btnApply.Enabled = false;
        }

        /// <summary>
        /// Сохраняет текущие зависимости
        /// </summary>
        /// <returns>true - если сохранение прошло удачно, false в противном случае</returns>
        private bool saveCurrentDependences()
        {
            WorkList lstDependences = new WorkList();
            WorkList lstDeleteDependences = new WorkList();
            foreach (WorkItem workItem in workItemList)
            {
                if (workItem.Checked)
                {
                    lstDependences.Add(projectCopy.worklist.getWorkByName(workItem.Text));
                }
                else
                {
                    lstDeleteDependences.Add(projectCopy.worklist.getWorkByName(workItem.Text));
                }
            }

            selectedWork.RemoveDependences(lstDeleteDependences);

            if (projectCopy.TreeBuild(selectedWork, lstDependences, 0))
            {
                return false;
            }

            selectedWork.SetDependences(lstDependences);
            
            return true;
        }

        #endregion

        #region Обработчики событий
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
            DialogResult = DialogResult.Cancel;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!saveCurrentDependences())
            {
                MessageBox.Show("Нельзя установить работы в такой последовательности - образуется цикл", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                project = (Project)projectCopy.Clone();
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private void cbxWorks_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!saveCurrentDependences())
            {
                cbxWorks.SelectedItem = selectedWork.Name;
                if (first)
                {
                    MessageBox.Show("Нельзя установить работы в такой последовательности - образуется цикл", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    first = false;
                }
                else
                {
                    first = true;
                }
            }
            else
            {
                first = true;
                selectedWork = projectCopy.worklist.getWorkByName(cbxWorks.SelectedItem.ToString());
                setListViewWorks();
            }
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            if (!saveCurrentDependences())
            {
                MessageBox.Show("Нельзя установить работы в такой последовательности - образуется цикл");
            }
            else
            {
                project = (Project)projectCopy.Clone();
                btnApply.Enabled = false;
            }
        }

        private void listViewWorks_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            btnApply.Enabled = true;
        }
        #endregion

    }
}
